//
//  ViewController.m
//  UIScrollVIewGrid
//
//  Created by David Skrundz on 12-07-17.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	
	_buttons = [[NSMutableArray alloc] init];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - IBAction

- (IBAction)add:(id)sender {
	[self addItem];
}

- (void)remove:(id)sender {
	[self removeItem:sender];
}

#pragma mark - Arrangement

- (void)addItem {
	int row = floor([_buttons count] / 5);
    int column = ([_buttons count] - (row * 5));
	
	UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
	[colorView setUserInteractionEnabled:NO];
	[colorView setBackgroundColor:[UIColor colorWithRed:((arc4random() % 100) / 100.0) green:((arc4random() % 100) / 100.0) blue:((arc4random() % 100) / 100.0) alpha:0.5]];
	
	UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
	[button addSubview:colorView];
    [button addTarget:self action:@selector(removeItem:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = [_buttons count];
    // This is the title of where they were created, so we can see them move.s
    [button setTitle:[NSString stringWithFormat:@"%d, %d", row, column] forState:UIControlStateNormal];
	
    [_buttons addObject:button];
    [scrollView addSubview:button];
	// This will add 10px padding on the bottom as well as the top and left.
    [scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}

- (void)removeItem:(id)sender {
	UIButton *button = (UIButton *)sender;
    [button removeFromSuperview];
    [_buttons removeObjectAtIndex:button.tag];
	
    [self rearrangeItems:button.tag];
}

- (void)rearrangeItems:(int)startIndex {
	for (UIButton *button in _buttons) {
        // Shift the tags down one
        if (button.tag > startIndex) {
            button.tag -= 1;
			// Recalculate Position
			int row = floor(button.tag / 5);
			int column = (button.tag - (row * 5));
			// Move
			button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
			if (button.tag == [_buttons count] - 1) {
				[scrollView setContentSize:CGSizeMake(300, row*61+16+60)];
			}
		}
    }
}

@end